from rest_framework.generics import RetrieveAPIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView

from activity.serializers.gatherings import GatheringsSerializer

from scf_project.utils.pagenum import PageNum
from activity.models import Gathering
from activity.serializers.gatherings import GatheringsIDSerializer


# 活动详情
class GatheringsIdView(RetrieveAPIView):
    """活动详情"""
    serializer_class = GatheringsIDSerializer
    queryset = Gathering.objects.all()

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)

        # 渲染数据
        data_dict = serializer.data
        image_url = data_dict['image']

        # 修改url地址
        image_url = image_url.replace(f'8000/gatherings/{data_dict["id"]}/', '8888/')
        data_dict['image'] = image_url

        return Response(data_dict)


# 活动列表
class GatheringsView(ListAPIView):
    serializer_class = GatheringsSerializer
    pagination_class = PageNum

    def get_queryset(self):
        return Gathering.objects.all().order_by('id')

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)

            # 获取数据
            data_dict = serializer.data
            for data in data_dict:
                image = data['image']

                # 重构数据
                image = image.replace(f'8000/gatherings/', '8888/')
                data['image'] = image

            return self.get_paginated_response(data_dict)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


# 活动报名
class GatheringsJoinView(APIView):
    def post(self, request, id):
        # 获取用户对象
        user = request.user
        try:
            # 获取活动对象
            gathering = Gathering.objects.get(id=id)

            users = gathering.users.all()

            if user in users:

                gathering.users.remove(user)
                return Response({'message': '取消报名成功',
                                 'success': True})

            else:
                gathering.users.add(user)

                return Response({'message': '报名成功',
                                 'success': True})
        except Exception as e:
            return Response({'message': '报名失败',
                             'success': False})
